import React, { Component } from 'react';
import axios from 'axios';
import './transfer.css';
import InputNum from '../input_num';
import { getCurrentTimeText } from '../../utils/timeUtils';
import { getTransferToken } from '../../api/';
import { getAudio } from '../../api/';

export default class index extends Component {

    componentDidMount() {
        let param = new URLSearchParams();
        param.append("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz");
        param.append("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6");
        param.append("grant_type", "client_credentials");
        getTransferToken(param).then(response => {
            const { access_token } = response;
            this.setState({ access_token })
        }).catch(err => {
            alert('网络异常，请稍微刷新重试...');
            console.error(err);
        })
    }

    state = {
        voiceType: [
            { id: 'v1', name: '普通女声', value: '0' },
            { id: 'v2', name: '普通男声', value: '1' },
            { id: 'v3', name: '情感合成-度逍遥', value: '3' },
            { id: 'v4', name: '情感合成-度丫丫', value: '4' }
        ],
        access_token: '',
        chooseVoice: '0',
        speakSpeed: 5,    // 语速
        voiceTone: 5,    // 语调
        speakVolumn: 5,    // 音量
    }

    setSpeakSpeed = (num) => {
        this.setState({ speakSpeed: num })
    }

    setVoiceTone = (num) => {
        this.setState({ voiceTone: num })
    }

    setSpeakVolumn = (num) => {
        this.setState({ speakVolumn: num })
    }

    transferText = () => {
        const inputText = this.inputNode.value;
        if (inputText.length > 2000) {
            alert('每次转换的文字不得超过2000字符');
            return;
        }
        let param = new URLSearchParams();
        param.append("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz");
        param.append("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6");
        param.append("grant_type", "client_credentials");

        getTransferToken(param).then(response => {
            console.log('请求成功', response);
            this.createVoiceByText(inputText);
        }).catch(err => {
            console.log(err);
            alert('未知异常，请联系管理员...');
            return;
        })
    }
    // 
    getCurrentTime = () => {
        let timeText = getCurrentTimeText();
        this.createVoiceByText(timeText);
    }

    audition = (num) => {
        return () => {
            switch (num) {
                // 试听文本框文本
                case 1:
                    const inputText = this.inputNode.value;
                    this.auditionByText(inputText);
                    break;
                // 试听时间戳文本
                case 2:
                    let timeText = getCurrentTimeText();
                    this.auditionByText(timeText);
                    break;
            }
        }
    }

    auditionByText = (text) => {
        const { access_token, speakSpeed, voiceTone, speakVolumn, chooseVoice } = this.state;
        let param2 = new URLSearchParams();
        param2.append("tex", text);
        param2.append("tok", access_token);
        param2.append("cuid", "12345postman");
        param2.append("ctp", "1");
        param2.append("lan", "zh");
        param2.append("spd", speakSpeed);
        param2.append("pit", voiceTone);
        param2.append("vol", speakVolumn);
        param2.append("per", chooseVoice);
        param2.append("aue", "3");
        getAudio(param2).then(response => {
            let blob = new Blob([response]);
            let href = URL.createObjectURL(blob);
            this.audioNode.src = href;
            this.audioNode.play();
        }).catch(err => {
            console.error(err);
            alert('网络异常，请稍后再试或联系管理员');
        })
    }

    createVoiceByText = (text) => {
        const { access_token, speakSpeed, voiceTone, speakVolumn, chooseVoice } = this.state;
        let param2 = new URLSearchParams();
        param2.append("tex", text);
        param2.append("tok", access_token);
        param2.append("cuid", "12345postman");
        param2.append("ctp", "1");
        param2.append("lan", "zh");
        param2.append("spd", speakSpeed);
        param2.append("pit", voiceTone);
        param2.append("vol", speakVolumn);
        param2.append("per", chooseVoice);
        param2.append("aue", "3");
        getAudio(param2).then(
            response => {
                console.log(response)
                // 创建隐藏的可下载链接
                let eleLink = document.createElement('a');
                eleLink.download = 'test.mp3';
                eleLink.style.display = 'none';
                // 字符内容转变成blob地址
                let blob = new Blob([response]);
                eleLink.href = URL.createObjectURL(blob);
                // 触发点击
                document.body.appendChild(eleLink);
                eleLink.click();
                // 然后移除
                document.body.removeChild(eleLink);
            }
        ).catch(err => {
            console.error(err);
            alert('网络出错，请刷新重试，或者联系管理员...');
        })
    }

    render() {
        const { chooseVoice, speakSpeed, voiceTone, speakVolumn } = this.state;
        return (
            <div className="option">
                请输入要转换的文字:<br /><input ref={c => this.inputNode = c} type="textarea" className="input-text" />
                <br />
                声音：
                {
                    this.state.voiceType.map(ele => {
                        return (
                            <span key={ele.id}>
                                <input id={ele.id} type="radio" name="voice" value={ele.value} checked={ele.value === chooseVoice} onChange={(e) => this.setState({ chooseVoice: e.target.value })} />
                                <label htmlFor={ele.id}>{ele.name}</label>
                            </span>
                        )
                    })
                }
                <br />
                <InputNum count={speakSpeed} setCount={this.setSpeakSpeed} >语速（取值0-15）：</InputNum><br />
                <InputNum count={voiceTone} setCount={this.setVoiceTone} >音调（取值0-15）：</InputNum><br />
                <InputNum count={speakVolumn} setCount={this.setSpeakVolumn} >音量（取值0-15）：</InputNum><br />
                <button onClick={this.transferText}>点击转换</button>&nbsp;&nbsp;
                <button onClick={this.audition(1)}>试听一下</button>
                <br />
                <button className="option" onClick={this.getCurrentTime}>快速生成时间戳播报</button>&nbsp;&nbsp;
                <button className="option" onClick={this.audition(2)}>试听一下</button>
                <br />
                (注意，时间戳的试听只能试听当前点击的时间，下载后得到的时间以点击生成按钮的时间为准)
                <hr />
                <audio ref={e => this.audioNode = e} width="660" height="364" controls="controls"></audio>
            </div>
        )
    }
}
